package com.dkh.recommend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkh.recommend.dto.Result;
import com.dkh.recommend.dto.UserDTO;
import com.dkh.recommend.entity.TbFollow;
import com.dkh.recommend.entity.TbUser;
import com.dkh.recommend.mapper.TbFollowMapper;
import com.dkh.recommend.service.ITbFollowService;
import com.dkh.recommend.service.ITbUserService;
import com.dkh.recommend.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.dkh.recommend.utils.RedisConstants.FOLLOW_KEY;

@Slf4j
@Service
@Transactional
public class ITbFollowServiceImpl extends ServiceImpl<TbFollowMapper, TbFollow> implements ITbFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    private ITbUserService userService;
//    构造器注入防止循环依赖
    public ITbFollowServiceImpl(ITbUserService userService) {
        this.userService = userService;
    }

    /**
     * 查看我的关注列表
     * @return
     */
    @Override
    public Result MyFollowList() {

//        1.获取当前用户id
        Long userId = UserHolder.getUser().getUserId();
        String key = FOLLOW_KEY+userId;
//        2.获取关注集合set
        Set<String> followSet = stringRedisTemplate.opsForSet().members(key);
        if (followSet != null && !followSet.isEmpty() && followSet.size() > 0){
//        有缓存集合
//            解析关注集合set
            List<Long> ids1 = followSet.stream().map(Long::valueOf).collect(Collectors.toList());
//           将ids查询为UserList
            List<TbUser> tbUsers1 = userService.listByIds(ids1);
//            将查询到的userList转换为UserDtoList
            List<UserDTO> userDTOS1 = BeanUtil.copyToList(tbUsers1, UserDTO.class);
//            返回信息
            return Result.ok(userDTOS1);
        }
//        4.数据库查询获取关注列表
        LambdaQueryWrapper<TbFollow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbFollow::getUserId,userId);
        List<TbFollow> followList = this.list(queryWrapper);
//        5.将查询到的关注列表存入redis的set集合中
//        根据关注列表查询用户信息UserDTO
        List<Long> userIds = new ArrayList<>();
        followList.stream().forEach(follow->{
            userIds.add(follow.getFollowUserId());
            stringRedisTemplate.opsForSet().add(key,follow.getFollowUserId().toString());
        });
//        查询用户信息
        List<TbUser> userList = userService.listByIds(userIds);
//        用beanUtil将userList转换为UserDTOList
        List<UserDTO> userDTOS = BeanUtil.copyToList(userList, UserDTO.class);
//        返回用户列表
        return Result.ok(userDTOS);
    }

    /**
     * 关注/取消关注
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result Follow(Long followUserId, Boolean isFollow) {
//        获取登录用户的Id
        Long userId = UserHolder.getUser().getUserId();
//        Redis缓存key
        String key = FOLLOW_KEY+userId;
        String msg = "成功";
//        判断关注还是取关
        if (!isFollow){
//            还未关注
//            关注，新增数据
            TbFollow tbFollow = new TbFollow();
            tbFollow.setUserId(userId);
            tbFollow.setFollowUserId(followUserId);
            boolean isSuccess = this.save(tbFollow);
            if (isSuccess){
                stringRedisTemplate.opsForSet().add(key,followUserId.toString());
                msg = "关注成功！";
            }else {
                Result.fail("关注失败！请重试");
            }
        }else {
            //            已关注
//            取消关注，删除
            LambdaQueryWrapper<TbFollow> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(TbFollow::getUserId,userId)
                    .eq(TbFollow::getFollowUserId,followUserId);
            boolean isRemove = this.remove(queryWrapper2);
            if (isRemove){
//                取关成功，从缓存删除
                stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
                msg = "取关成功！";
            }else {
                Result.fail("取消关注失败！请重试");
            }
        }

        return Result.ok(msg);
    }

    /**
     *是否关注
     * @param followUserId
     * @return
     */
    @Override
    public Result IsFollow(Long followUserId) {
        //        获取登录用户的Id
        Long userId = UserHolder.getUser().getUserId();
//        从数据库查询是否已经关注该用户
        LambdaQueryWrapper<TbFollow> queryWrapper  = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbFollow::getUserId,userId)
                .eq(TbFollow::getFollowUserId,followUserId);
        List<TbFollow> tbFollows = this.list(queryWrapper);
        return Result.ok(tbFollows.size() > 0);
    }

    /**
     * 共同关注
     * @param id
     * @return
     */
    @Override
    public Result FollowCommons(Long id) {
        //        获取登录用户的Id
        Long userId = UserHolder.getUser().getUserId();
//        Redis缓存key
        String key = FOLLOW_KEY+userId;
//        求交集
        String key2 = FOLLOW_KEY + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (intersect == null || intersect.isEmpty()){
//            无交集
            return Result.ok(Collections.emptyList());
        }
//        3.解析id集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
//        根据ids查询用户
        List<TbUser> tbUsers = userService.listByIds(ids);
//        将UserList转换为UserDTOList
        List<UserDTO> userDTOS = BeanUtil.copyToList(tbUsers, UserDTO.class);
        return Result.ok(userDTOS);
    }
}
